package com.iflytek.jcy.supervise.job.component.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.cache.support.NoOpCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;

/**
 * @author <a href=mailto:ktyi@iflytek.com>伊开堂</a>
 * @date 2020/6/9
 */
@Configuration
@EnableCaching
public class CacheConfig {
    @Autowired
    private Environment env;

    /**
     * 默认缓存配置
     * @return
     */
    @Bean("defaultCacheManager")
    @Primary
    public CacheManager defaultCacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        cacheManager.setCacheSpecification("initialCapacity=1000, maximumSize=1000, expireAfterWrite=30s, recordStats");
        return cacheManager;
    }

    private CacheManager buildCacheManager(CacheProperties properties, String name) {
        if (env.getProperty("cache.enable", Boolean.class)) {
            CaffeineCacheManager cacheManager = new CaffeineCacheManager(name);
            cacheManager.setCacheSpecification("initialCapacity=100, maximumSize=500, expireAfterWrite=1m, recordStats");
            return cacheManager;
        }

        return new NoOpCacheManager();
    }
}